package whf.framework.meta.util;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import whf.framework.config.ApplicationConfig;
import whf.framework.dao.DAO;
import whf.framework.service.Service;
import whf.framework.util.Pair;
import whf.framework.util.StringUtils;
import whf.framework.util.TypeUtils;
import whf.framework.util.Utils;

/**
 * 从元数据中生成Spring的配置
 * @author wanghaifeng
 * @create Apr 24, 2007 12:52:53 PM
 * 
 */
public final class SpringConfigBuilder {
	
	private SpringConfigBuilder(){
		
	}
	
	/**
	 * 获取配置模板
	 * @modify wanghaifeng Apr 24, 2007 1:01:52 PM
	 * @return
	 */
	private static String getSpringConfigTemplate(){
		String template = ApplicationConfig.getInstance().getValue("template.spring");
		if(!StringUtils.isEmpty(template)){
			return template;
		}
		InputStream is = SpringConfigBuilder.class.getResourceAsStream("SpringConfigBuilder.config");
		try{
			byte[] buff = new byte[is.available()];
			is.read(buff, 0, buff.length);
			template = new String(buff);
			return template;
		}catch(Exception e){
			//do nothing
		}
		throw new IllegalStateException("No template files!");
	}
	
	/**
	 * 生成配置
	 * @modify wanghaifeng Apr 24, 2007 1:39:02 PM
	 * @param metas
	 * @return
	 */
	public static List<Pair<whf.framework.meta.entity.Object, String>> buildConfigs(List<whf.framework.meta.entity.Object> metas){
		List<Pair<whf.framework.meta.entity.Object, String>> result = Utils.newArrayList();
		for(whf.framework.meta.entity.Object meta: metas){
			result.add(new Pair<whf.framework.meta.entity.Object, String>(meta, buildConfig(meta)));
		}
		return result;
	}
	
	/**
	 * 生成配置
	 * @modify wanghaifeng Apr 24, 2007 1:38:33 PM
	 * @param meta
	 * @return
	 */
	public static String buildConfig(whf.framework.meta.entity.Object meta){
		Map<String, String> map = Utils.newHashMap();
		map.put("{1}", meta.getDaoClassName());
		Class[] daoInterfaces = Utils.getClassByClassName(meta.getDaoClassName()).getInterfaces();
		for(Class c: daoInterfaces){
			if(TypeUtils.isExtendsFrom(c, DAO.class)){
				map.put("2", c.getName());
			}
		}
		map.put("{3}", meta.getDaoName());

		map.put("{4}", meta.getServiceClassName());
		Class[] serviceInterfaces = Utils.getClassByClassName(meta.getServiceClassName()).getInterfaces();
		for(Class c: serviceInterfaces){
			if(TypeUtils.isExtendsFrom(c, Service.class)){
				map.put("5", c.getName());
			}
		}
		map.put("{6}", meta.getDaoName());
		
		String name = StringUtils.capitalize(Utils.getClassByClassName(meta.getBoClassName()).getSimpleName());
		map.put("{7}", name);
		return StringUtils.replace2(map, getSpringConfigTemplate());
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(getSpringConfigTemplate());
	}
}
